<template>
  <div class="settings">
    <van-nav-bar safe-area-inset-top placeholder :title="$t('BasicSetting')" left-arrow fixed @click-left="onClickLeft" />
    <van-pull-refresh v-model="isLoading" :pulling-text="$t('PullingText')" :loosing-text="$t('PullingText')" :success-text="$t('refreshSuccee')" @refresh="onRefresh">
      <van-collapse class="marginTop15" v-model="activeNames">
        <van-collapse-item :title="$t('Datetime')" name="1">
          <datetimePTVue :times="LocalArr.datetimes"></datetimePTVue>
        </van-collapse-item>
        <van-collapse-item :title="$t('Language')" name="2">
          <languagePTVue :columns="langArr" :setValue="LocalArr.lang" :reg="71"></languagePTVue>
        </van-collapse-item>
        <van-collapse-item :title="$t('Ethernet')" name="3">
          <languagePTVue
            :setName="$t('IPmethod')"
            :columns="iPmethodArr"
            :reg="72"
            :setValue="LocalArr.IPmethodCode"
            @getFormData="setIPmethod"
          ></languagePTVue>
          <van-form @submit="IPAddressSubmit">
            <van-field
              v-model="LocalArr.ipaddressValue" 
              :label="$t('IPAddress')"
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixedIPAddress,message: `${$t('AddressError')}` }]" 
            />
            <van-field
              v-model="LocalArr.subnetmaskValue" 
              :label="$t('Subnetmask')" 
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixedSubnetmask,message: `${$t('AddressError')}` }]" 
            />
            <van-field
              v-model="LocalArr.defaultGatewayValue" 
              :label="$t('DefaultGateway')" 
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixedDefaultGateway,message: `${$t('AddressError')}` }]" 
            />
            <div class="factorBtnBox" v-if="isStatic">
              <van-button block round>{{$t('Save')}}</van-button>
            </div>
          </van-form>
          <tripFreVue :setName="$t('MacAddress')" :setValue="macAddress"></tripFreVue>
        </van-collapse-item>
        <van-collapse-item :title="$t('Charger')" name="4">
          <facMaxPTVue :setName="$t('ChargeMaxCurrent')" :setUntil="'A'" :setMin="'0.00'" :setMax="'25.00'" :setValue.sync="LocalArr.ChargeMaxCurrentValue" :reg="36"></facMaxPTVue>
          <facMaxPTVue :setName="$t('DischargeMaxCurrent')" :setUntil="'A'" :setMin="'0.00'" :setMax="'25.00'" :setValue.sync="LocalArr.DischargeMaxCurrentValue" :reg="37"></facMaxPTVue>
          <languagePTVue
            :setName="$t('GridTiedMinLimit')"
            :columns="backupModeArr"
            :reg="156"
            :setValue="LocalArr.GridTiedMinLimitCode"
            @getFormData="setGridTiedMinLimit"
          ></languagePTVue>
          <pfLockInPointPTVue :setName="$t('Grid-tiedMinCapacity')" :setUntil="'%'" :setMin="LocalArr.BatteryMinEnergyValue" :setMax="100" :setValue.sync="LocalArr.GridTiedMinCapacityValue" :reg="157" v-if="isGridTied"></pfLockInPointPTVue>
        </van-collapse-item>
        <van-collapse-item :title="$t('EPS')" name="5">
          <languagePTVue :setName="$t('Mute')" :columns="backupModeArr" :setValue="LocalArr.EPSMuteValue" :reg="67"></languagePTVue>
          <languagePTVue :setName="$t('Frequency')" :setUntil="'Hz'" :columns="EPSFrequencyArr" :setValue="LocalArr.EPSFrequencyValue" :reg="68"></languagePTVue>
          <languagePTVue
            :setName="$t('EpsBatLowAutoRecoverEn')"
            :columns="backupModeArr"
            :setValue="LocalArr.EpsBatLowAutoRecoverEnCode"
            :reg="168"
            @getFormData="setEpsBatLowAutoRecoverEn"
          ></languagePTVue>
          <pfLockInPointPTVue :setName="$t('MinCapacity')" :setUntil="'%'" :setMin="LocalArr.BatteryMinEnergyValue" :setMax="100" :setValue.sync="LocalArr.EpsBatMinCapacityValue" :reg="170" v-if="isEpsBatLowAutoRecoverEn"></pfLockInPointPTVue>
        </van-collapse-item>
        <van-collapse-item :title="$t('SystemSwitch')" name="6">
          <languagePTVue :columns="backupModeArr" :setValue="LocalArr.SystemSwitchValue" :reg="133"></languagePTVue>
        </van-collapse-item>
        <van-collapse-item :title="$t('WorkMode')" name="7">
          <languagePTVue
            :setName="$t('WorkMode')"
            :columns="solarModeArr"
            :reg="31"
            :setValue="LocalArr.SolarModeCode"
            @getFormData="setSolarMode"
          ></languagePTVue>
          <div v-if="isForceTimeUse">
            <van-divider>{{$t('period1')}}</van-divider>
            <div class="pltxt">{{$t('GridChargeContorl')}}</div>
            <van-field v-model="LocalArr.GridChargeContorlValue1" clickable readonly @click="showGridControl1 = true">
                <template #button>
                  <van-button size="small" round @click="setGridChargeContorl($event)" class="setbtn">{{$t('Save')}}</van-button>
                </template>
            </van-field>
            <van-popup v-model="showGridControl1" round position="bottom">
              <van-picker show-toolbar 
                :columns="backupModeArr" 
                @cancel="showGridControl1 = false" 
                @confirm="GridControl1Confirm"
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')" 
              />
            </van-popup>
            <chargeTimePTVue :setName="$t('ChargeStartTime')" :setValue="LocalArr.ChargeStartTime" :reg="38"></chargeTimePTVue>
            <chargeTimePTVue :setName="$t('ChargeEndTime')" :setValue="LocalArr.ChargeEndTime" :reg="39"></chargeTimePTVue>
          </div>
          <div v-if="isForceTimeUse">
            <van-divider>{{$t('period2')}}</van-divider>
            <div class="pltxt">{{$t('GridChargeContorl')}}</div>
            <van-field v-model="LocalArr.GridChargeContorlValue2" clickable readonly @click="showGridControl2 = true">
                <template #button>
                  <van-button size="small" round @click="setGridChargeContorl($event)" class="setbtn">{{$t('Save')}}</van-button>
                </template>
            </van-field>
            <van-popup v-model="showGridControl2" round position="bottom">
              <van-picker show-toolbar 
                :columns="backupModeArr" 
                @cancel="showGridControl2 = false" 
                @confirm="GridControl2Confirm"
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')" 
              />
            </van-popup>
            <chargeTimePTVue :setName="$t('ChargeStartTime')" :setValue="LocalArr.ChargeStartTime2" :reg="42"></chargeTimePTVue>
            <chargeTimePTVue :setName="$t('ChargeEndTime')" :setValue="LocalArr.ChargeEndTime2" :reg="43"></chargeTimePTVue>
          </div>
          <van-form @submit="BackupModeSubmit" v-if="isBackupMode">
            <van-field :value="LocalArr.backupMode" :label="$t('BackupFromGrid')" readonly clickable name="picker" input-align="right" @click="showBackup = true" />
            <van-popup v-model="showBackup" round position="bottom">
              <van-picker show-toolbar :columns="backupModeArr" 
                @cancel="showBackup = false" 
                @confirm="backupConfirm" 
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')"
              />
            </van-popup>
            <van-field v-model="LocalArr.BackupStartTime" :label="$t('ChargeStartTime')" clickable readonly name="picker" input-align="right" @click="showBackupStart = true" />
            <van-popup v-model="showBackupStart" round position="bottom">
              <van-datetime-picker
                v-model="currentTimeStart"
                type="time"
                @cancel="showBackupStart = false"
                @confirm="BackupStartConfirm"
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')"
              />
            </van-popup>
            <van-field v-model="LocalArr.BackupEndTime" :label="$t('ChargeEndTime')" clickable readonly name="picker" input-align="right" @click="showBackupEnd = true" />
            <van-popup v-model="showBackupEnd" round position="bottom">
              <van-datetime-picker
                v-model="currentTimeEnd"
                type="time"
                @cancel="showBackupEnd = false"
                @confirm="BackupEndConfirm"
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')"
              />
            </van-popup>
            <div class="factorBtnBox">
              <van-button block round>{{$t('Save')}}</van-button>
            </div>
          </van-form>
        </van-collapse-item>
        <van-collapse-item title="Self Test" name="8" v-if="safety==9">
          <van-cell title="Self Test Start" is-link @click="goSelftTest(1)" />
          <van-cell title="Self Test Results" is-link @click="goSelftTest(2)" />
        </van-collapse-item>
      </van-collapse>
    </van-pull-refresh>
  </div>
</template>

<script>
import datetimePTVue from '../../../components/DateTime/BDDateTimePT'
import languagePTVue from '../../../components/Language/BDLanguagePT'
import tripFreVue from '../../../components/TripFre/TripFre'
import pfLockInPointPTVue from '../../../components/PfLockInPoint/BDPfLockInPointPT'
import facMaxPTVue from '../../../components/FacMax/BDFacMaxPT'
import chargeTimePTVue from '../../../components/ChargeTime/BDChargeTimePT'
import tstartVue from '../../../components/TStart/BDTStart'

export default {
  components:{
    datetimePTVue,
    languagePTVue,
    tripFreVue,
    pfLockInPointPTVue,
    facMaxPTVue,
    chargeTimePTVue,
    tstartVue
  },
  data(){
    return {
      isLoading:false,
      activeNames:[],
      safety:sessionStorage.getItem('safety'),
      langArr:[this.$t('English'),this.$t('German'),this.$t('French'),this.$t('Polish')],
      iPmethodArr:['DHCP','Static'],
      isStatic:false,
      macAddress:'',
      EPSFrequencyArr:['50','60'],
      isEpsBatLowAutoRecoverEn:false,
      isForceTimeUse:false,
      isBackupMode:false,
      solarModeArr:[this.$t('SelfUse'),this.$t('ForceTimeUse'),this.$t('BackupMode'),this.$t('FeedInPriority')],
      backupModeCode:'',
      showBackup:false,
      backupModeArr:[this.$t('Disable'),this.$t('Enable')],
      showBackupStart:false,
      currentTimeStart:'',
      currentTimeEnd:'',
      showBackupEnd:false,
      DischargeCutOffPoint_DifferentEN:'',
      isGridTied:false,
      showGridControl1:false,
      GridChargeContorlValue1Code:'',
      showGridControl2:false,
      GridChargeContorlValue2Code:'',
      LocalArr:{
        datetimes:'',
        lang:'',
        IPmethodCode:'',
        ipaddressValue:'',
        subnetmaskValue:'',
        defaultGatewayValue:'',
        BatteryMinEnergyValue:'',
        ChargeMaxCurrentValue:'',
        DischargeMaxCurrentValue:'',
        GridTiedMinCapacityValue:'',
        GridTiedMinLimitCode:'',
        EPSMuteValue:'',
        EPSFrequencyValue:'',
        EpsBatLowAutoRecoverEnCode:'',
        EpsBatMinCapacityValue:'',
        SystemSwitchValue:'',
        SolarModeCode:'',
        ChargeStartTime:'',
        ChargeEndTime:'',
        ChargeStartTime2:'',
        ChargeEndTime2:'',
        backupMode:'',
        BackupStartTime:'',
        BackupEndTime:'',
        GridChargeContorlValue1:'',
        GridChargeContorlValue2:''
      }
    }
  },
  methods: {
    onClickLeft(){
      this.$router.push({path:'/bdsetting'});
    },
    goSelftTest(num){
      sessionStorage.setItem('setFrom','/bdx3hybridg1basicPT');
      if(num==1){
        this.$router.push({path:'/bdteststart'});
      }else{
        this.$router.push({path:'/bdtestresult'});
      }
    },
    fixedIPAddress(val){
      return this.comm.fixedIPAddress(val);
    },
    fixedSubnetmask(val){
      return this.comm.fixedSubnetmask(val);
    },
    fixedDefaultGateway(val){
      return this.comm.fixedDefaultGateway(val);
    },
    backupConfirm(value,i){
      this.showBackup=false;
      this.LocalArr.backupMode=value;
      this.backupModeCode=i;
    },
    BackupStartConfirm(val){
      this.showBackupStart=false;
      this.LocalArr.BackupStartTime=val;
    },
    BackupEndConfirm(val){
      this.showBackupEnd=false;
      this.LocalArr.BackupEndTime=val;
    },
    GridControl1Confirm(val,i){
      this.showGridControl1=false;
      this.LocalArr.GridChargeContorlValue1=val;
      this.GridChargeContorlValue1Code=i;
    },
    GridControl2Confirm(val,i){
      this.showGridControl2=false;
      this.LocalArr.GridChargeContorlValue2=val;
      this.GridChargeContorlValue2Code=i;
    },
    async getData(){
      this.comm.loadingShow();
      let datas = await this.SETAPI.LocalIn({'optType':'ReadSetData','pwd':sessionStorage.getItem('bdPwd')});
      if(datas!=null||datas!=undefined){
        let dataArr = datas;
        this.safety=dataArr[4];
        sessionStorage.setItem('safety',this.safety);
        let year=dataArr[29];
        let month=dataArr[28]>=10?dataArr[28]:"0"+dataArr[28];
        let day=dataArr[27]>=10?dataArr[27]:"0"+dataArr[27];
        let hour=dataArr[26]>=10?dataArr[26]:"0"+dataArr[26];
        let minute=dataArr[25]>=10?dataArr[25]:"0"+dataArr[25];
        this.LocalArr.datetimes=`${year+2000}-${month}-${day} ${hour}:${minute}`;
        this.LocalArr.lang=dataArr[67];
        this.LocalArr.IPmethodCode=dataArr[68];
        //判断用户的选择
        if(this.LocalArr.IPmethodCode==1){
          this.isStatic=true;
        }else{
          this.isStatic=false;
        }
        this.LocalArr.ipaddressValue=`${dataArr[53]}.${dataArr[54]}.${dataArr[55]}.${dataArr[56]}`;
        this.LocalArr.subnetmaskValue=`${dataArr[153]}.${dataArr[154]}.${dataArr[155]}.${dataArr[156]}`;
        this.LocalArr.defaultGatewayValue=`${dataArr[57]}.${dataArr[58]}.${dataArr[59]}.${dataArr[60]}`;
        if(dataArr[157]==null||dataArr[157]==undefined||dataArr[158]==null||dataArr[158]==undefined||dataArr[159]==null||dataArr[159]==undefined){
          this.macAddress="";
        }else{
          this.macAddress=`${this.comm.bit8low(1,dataArr[157])}-${this.comm.bit8high(1,dataArr[157])}-${this.comm.bit8low(1,dataArr[158])}-${this.comm.bit8high(1,dataArr[158])}-${this.comm.bit8low(1,dataArr[159])}-${this.comm.bit8high(1,dataArr[159])}`;
        }
        this.LocalArr.BatteryMinEnergyValue=dataArr[31];
        this.LocalArr.ChargeMaxCurrentValue=dataArr[35]/100;
        this.LocalArr.DischargeMaxCurrentValue=dataArr[36]/100;
        this.LocalArr.GridTiedMinCapacityValue=dataArr[170];
        this.LocalArr.GridTiedMinLimitCode=dataArr[169];
        /*判断用户的选择*/
        if(this.LocalArr.GridTiedMinLimitCode==1){
          this.isGridTied=true;
        }else{
          this.isGridTied=false;
        }
        this.LocalArr.EPSMuteValue=dataArr[64];
        this.LocalArr.EPSFrequencyValue=dataArr[65];
        this.LocalArr.EpsBatLowAutoRecoverEnCode=dataArr[179];
        /*判断用户选择*/
        if(dataArr[179]=='1'){
          this.isEpsBatLowAutoRecoverEn=true;
        }else{
          this.isEpsBatLowAutoRecoverEn=false;
        }
        this.LocalArr.EpsBatMinCapacityValue=dataArr[181];
        this.LocalArr.SystemSwitchValue=dataArr[98];
        this.LocalArr.SolarModeCode=dataArr[30];
        /*判断用户的选择*/
        if(this.LocalArr.SolarModeCode==1){
          this.isForceTimeUse=true;
        }else{
          this.isForceTimeUse=false;
        }
        if(this.LocalArr.SolarModeCode==2){
          this.isBackupMode=true;
        }else{
          this.isBackupMode=false;
        }
        
        if(dataArr[61]==0){
          this.GridChargeContorlValue1Code=0;
          this.GridChargeContorlValue2Code=0;
          this.LocalArr.GridChargeContorlValue1=this.backupModeArr[0];
          this.LocalArr.GridChargeContorlValue2=this.backupModeArr[0];
        }else if(dataArr[61]==1){
          this.GridChargeContorlValue1Code=1;
          this.GridChargeContorlValue2Code=0;
          this.LocalArr.GridChargeContorlValue1=this.backupModeArr[1];
          this.LocalArr.GridChargeContorlValue2=this.backupModeArr[0];
        }else if(dataArr[61]==2){
          this.GridChargeContorlValue1Code=0;
          this.GridChargeContorlValue2Code=1;
          this.LocalArr.GridChargeContorlValue1=this.backupModeArr[0];
          this.LocalArr.GridChargeContorlValue2=this.backupModeArr[1];
        }else if(dataArr[61]==3){
          this.GridChargeContorlValue1Code=1;
          this.GridChargeContorlValue2Code=1;
          this.LocalArr.GridChargeContorlValue1=this.backupModeArr[1];
          this.LocalArr.GridChargeContorlValue2=this.backupModeArr[1];
        }

        let workMode1StartHour=dataArr[37];
        let workMode1StartMinute=dataArr[38];
        workMode1StartHour=parseInt(workMode1StartHour)>=10?workMode1StartHour:"0"+workMode1StartHour;
        workMode1StartMinute=parseInt(workMode1StartMinute)>=10?workMode1StartMinute:"0"+workMode1StartMinute;
        this.LocalArr.ChargeStartTime=`${workMode1StartHour}:${workMode1StartMinute}`;

        let workMode1EndHour=dataArr[39];
        let workMode1EndMinute=dataArr[40];
        workMode1EndHour=parseInt(workMode1EndHour)>=10?workMode1EndHour:"0"+workMode1EndHour;
        workMode1EndMinute=parseInt(workMode1EndMinute)>=10?workMode1EndMinute:"0"+workMode1EndMinute;
        this.LocalArr.ChargeEndTime=`${workMode1EndHour}:${workMode1EndMinute}`;

        let workMode2StartHour=dataArr[45];
        let workMode2StartMinute=dataArr[46];
        workMode2StartHour=parseInt(workMode2StartHour)>=10?workMode2StartHour:"0"+workMode2StartHour;
        workMode2StartMinute=parseInt(workMode2StartMinute)>=10?workMode2StartMinute:"0"+workMode2StartMinute;
        this.LocalArr.ChargeStartTime2=`${workMode2StartHour}:${workMode2StartMinute}`;

        let workMode2EndHour=dataArr[47];
        let workMode2EndMinute=dataArr[48];
        workMode2EndHour=parseInt(workMode2EndHour)>=10?workMode2EndHour:"0"+workMode2EndHour;
        workMode2EndMinute=parseInt(workMode2EndMinute)>=10?workMode2EndMinute:"0"+workMode2EndMinute;
        this.LocalArr.ChargeEndTime2=`${workMode2EndHour}:${workMode2EndMinute}`;

        this.backupModeCode=dataArr[135];
        this.LocalArr.backupMode=this.backupModeArr[this.backupModeCode];

        let workMode3StartHour=dataArr[136];
        let workMode3StartMinute=dataArr[137];
        workMode3StartHour=parseInt(workMode3StartHour)>=10?workMode3StartHour:"0"+workMode3StartHour;
        workMode3StartMinute=parseInt(workMode3StartMinute)>=10?workMode3StartMinute:"0"+workMode3StartMinute;
        this.LocalArr.BackupStartTime=`${workMode3StartHour}:${workMode3StartMinute}`;

        let workMode3EndHour=dataArr[138];
        let workMode3EndMinute=dataArr[139];
        workMode3EndHour=parseInt(workMode3EndHour)>=10?workMode3EndHour:"0"+workMode3EndHour;
        workMode3EndMinute=parseInt(workMode3EndMinute)>=10?workMode3EndMinute:"0"+workMode3EndMinute;
        this.LocalArr.BackupEndTime=`${workMode3EndHour}:${workMode3EndMinute}`;

        //GridTiedMinCapacity设置项需要做判断
        this.DischargeCutOffPoint_DifferentEN=dataArr[169];
      }else{
        this.comm.tipsShow('InvNoResponse');
      }
    },
    //设置IPmethod
    setIPmethod(data){
      /*判断用户的选择*/
      if(data==1){
        this.isStatic=true;
      }else{
        this.isStatic=false;
      }
    },
    //设置Ethernet
    IPAddressSubmit(){
      //数据处理
      let arr1=this.LocalArr.ipaddressValue.split(".");
      let arr2=this.LocalArr.subnetmaskValue.split(".");
      let arr3=this.LocalArr.defaultGatewayValue.split(".");
      this.comm.bdSetIP(arr1,arr2,arr3);
    },
    //设置Grid-TiedMinLimit
    setGridTiedMinLimit(data){
      /*判断用户的选择*/
      if(data==1){
        this.isGridTied=true;
      }else{
        this.isGridTied=false;
      }
    },
    //设置EpsBatLowAutoRecoverEn
    setEpsBatLowAutoRecoverEn(data){
      /*判断用户选择*/
      if(data==1){
        this.isEpsBatLowAutoRecoverEn=true;
      }else{
        this.isEpsBatLowAutoRecoverEn=false;
      }
    },
    //设置SolarMode
    setSolarMode(data){
      /*判断用户的选择*/
      if(data==1){
        this.isForceTimeUse=true;
      }else{
        this.isForceTimeUse=false;
      }
      if(data==2){
        this.isBackupMode=true;
      }else{
        this.isBackupMode=false;
      }
    },
    //设置BackupMode
    BackupModeSubmit(){
      let startArr=this.LocalArr.BackupStartTime.split(":");
      let endArr=this.LocalArr.BackupEndTime.split(":");
      let formData=[
        {'reg':125,'val':this.backupModeCode+''},
        {'reg':126,'val':startArr[0]+''},
        {'reg':127,'val':startArr[1]+''},
        {'reg':128,'val':endArr[0]+''},
        {'reg':129,'val':endArr[1]+''}
      ];
      this.comm.bdSetDataPT(5,formData);
    },
    //设置GridChargeContorl
    setGridChargeContorl(e){
      e.stopPropagation();
      let value=0;
      if(this.GridChargeContorlValue1Code==0&&this.GridChargeContorlValue2Code==0){
        value=0;
      }else if(this.GridChargeContorlValue1Code==1&&this.GridChargeContorlValue2Code==0){
        value=1;
      }else if(this.GridChargeContorlValue1Code==0&&this.GridChargeContorlValue2Code==1){
        value=2;
      }else if(this.GridChargeContorlValue1Code==1&&this.GridChargeContorlValue2Code==1){
        value=3;
      }
      this.comm.bdSetDataPT(1,[{'reg':64,'val':value}]);
    },
    onRefresh(){
      this.isLoading = false;
      for(let i in this.LocalArr){
        this.LocalArr[i]='';
      }
      this.getData();
    }
  },
  mounted(){
    setTimeout(()=>{
      this.getData();
    },1000);
  }
}
</script>

<style scoped lang="less">

</style>
